package com.pda.yuanjing.pages.main;

import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.LoginBeanOut;
import com.pda.yuanjing.database.DataBaseControl;
import com.pda.yuanjing.message.MessageWarp;
import com.pda.yuanjing.pages.codereplace.CodeReplaceActivity;
import com.pda.yuanjing.pages.custombill.CBillActivity;
import com.pda.yuanjing.pages.custombill.scanf.ScanfActivity;
import com.pda.yuanjing.pages.dealerscanf.DealerScanfActivity;
import com.pda.yuanjing.pages.fucode.FuCodeActivity;
import com.pda.yuanjing.pages.inbill.InBillActivity;
import com.pda.yuanjing.pages.inbilln.list.BillnActivity;
import com.pda.yuanjing.pages.jdpd.JDBillActivity;
import com.pda.yuanjing.pages.jdpd.add.JDBillAddActivity;
import com.pda.yuanjing.pages.modpass.ModfiyPassActivity;
import com.pda.yuanjing.pages.outbill.OutBillActivity;
import com.pda.yuanjing.pages.pro.ProBillActivity;
import com.pda.yuanjing.pages.smqc.CodeClearActivity;
import com.pda.yuanjing.pages.sybom.bomQueryActivity;
import com.pda.yuanjing.pages.sybz.BZActivity;
import com.pda.yuanjing.pages.sycx.QueryActivity;
import com.pda.yuanjing.pages.returnscanf.ReturnScanfActivity;
import com.pda.yuanjing.pages.sybm.BMBillActivity;
import com.pda.yuanjing.pages.kccx.SYKCActivity;
import com.pda.yuanjing.pages.kcpd.PDBillActivity;
import com.pda.yuanjing.pages.sytj.TJActivity;
import com.pda.yuanjing.pages.syzs.SYZSActivity;
import com.pda.yuanjing.pages.tpzz.TpzzActivity;
import com.pda.yuanjing.pages.xhbg.BGActivity;
import com.pda.yuanjing.pages.xsck.XSCKBillActivity;
import com.public_module.basemvp.activity.BaseActivity_noMVP;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.dialogs.ChooseDialog;
import com.public_module.tools.CheckVersion;
import com.public_module.tools.DensityUtil;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.shelwee.update.UpdateHelper;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends BaseActivity_noMVP {
    private String TAG = "MainActivity";

    @BindView(R.id.llmain)
    LinearLayout llmain;
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;

    ChooseDialog chooseDialog1;
    List<LoginBeanOut.DataBean.ShowInfoBean> list = new ArrayList<>();
    Gson gson;
    OkHttpClient client;
    ApiYJ apisync;
    public static  MainActivity mainActivity ;

    protected void initdata() {
        tvTitle.setText("主页"+" "+SharedPreferencesManger.getRealName());
        list = (List<LoginBeanOut.DataBean.ShowInfoBean>) getIntent().getSerializableExtra(PDApp.showListKey);
        ViewGroup.LayoutParams vlp = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < list.size(); i++) {
            TextView tv1 = new TextView(this);
            tv1.setLayoutParams(vlp);
            tv1.setText(list.get(i).getName());
            tv1.setTextSize(18);
            tv1.setTextColor(getResources().getColor(R.color.primary));
            tv1.setBackgroundResource(R.color.whitee);
            tv1.setPadding(10, 5, 0, 5);
            llmain.addView(tv1);

            GridView gridView1 = new GridView(this);
            gridView1.setLayoutParams(vlp);
            gridView1.setColumnWidth(122);
            gridView1.setGravity(Gravity.CENTER);
            gridView1.setHorizontalSpacing(0);
            gridView1.setVerticalSpacing(0);
            gridView1.setNumColumns(3);
            gridView1.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
            llmain.addView(gridView1);//将TextView 添加到子View 中
            MainAdapter mainAdapter = new MainAdapter(this, list.get(i).getList());
            gridView1.setAdapter(mainAdapter);
            DensityUtil.setListViewHeightBasedOnChildren(gridView1);
        }

        EventBus.getDefault().register(this);
        chooseDialog = new ChooseDialog(MainActivity.this, "是否退出程序", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                chooseDialog.dismiss();
                MainActivity.this.finish();
            }
        });
        WindowManager.LayoutParams lp = chooseDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;

        chooseDialog1 = new ChooseDialog(MainActivity.this, "是否清除缓存", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        chooseDialog1.dismiss();
                        DataBaseControl.clearData();
                        Glide.get(MainActivity.this).clearMemory();
//                        Glide.get(MainActivity.this).clearDiskCache();
                        showMsg("已成功清除缓存");
                    }
                });

            }
        });
        WindowManager.LayoutParams lp1 = chooseDialog1.getWindow().getAttributes();
        lp1.gravity = Gravity.CENTER;

        gson = new Gson();
        client = new OkHttpClient.Builder()
                .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                .followRedirects(false)
                .build();
        apisync = new Retrofit.Builder()
                .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                .client(client)
                .build().create(ApiYJ.class);

        UpdateHelper.setPackageName("com.pda.yuanjing");
        UpdateHelper updateHelper = new UpdateHelper.Builder(this)
                .checkUrl("http://" + SharedPreferencesManger.getHostName() + "/pda/APPSoftUpdate.ashx?cid=" + SharedPreferencesManger.getCid())
                .isAutoInstall(true)
                .build();
        updateHelper.check();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mainActivity = this;
        initdata();
        if(SharedPreferencesManger.getUpass().equals("000000")){
            intentToActivityWithoutParameter(this, ModfiyPassActivity.class);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            chooseDialog.show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @OnClick({R.id.iv_title_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
        }
    }

    public void getJDPage(int id, String name) {
        try {
            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("sy_downloadjiediandetail");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setProcessID(id);
            jieDianBeanIn.setJieDianName(name);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            JDBeanNewOut jdBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), JDBeanNewOut.class);
                            if (jdBeanOut.getErrcode() == 0 && jdBeanOut.getData() != null) {
                                jdBeanOut.getData().setProcessID(id+"");
                                jdBeanOut.getData().setJieDianName(name);
                                if (jdBeanOut.getData().getIsNeedBill()) {
                                    intentToActivityWithSParameter(MainActivity.this, CBillActivity.class,PDApp.process,jdBeanOut.getData());
                                } else {
                                    intentToActivityWithSParameter(MainActivity.this, ScanfActivity.class,PDApp.process,jdBeanOut.getData());
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageWarp messageWarp) {
        switch (messageWarp.getCode()) {
            case 1:
                intentToActivityWithoutParameter(this, InBillActivity.class);
                break;
            case 2:
                intentToActivityWithoutParameter(this, OutBillActivity.class);
                break;
            case 3:
                intentToActivityWithoutParameter(this, ReturnScanfActivity.class);
                break;
            case 4:
                intentToActivityWithoutParameter(this, BillnActivity.class);
                break;
            case 5:
                intentToActivityWithoutParameter(this, com.pda.yuanjing.pages.outbilln.list.BillnActivity.class);
                break;
            case 6:
                intentToActivityWithoutParameter(this, com.pda.yuanjing.pages.pron.list.BillnActivity.class);
                break;
            case 7:
                intentToActivityWithoutParameter(this, DealerScanfActivity.class);
                break;
            case 8:
                intentToActivityWithoutParameter(this, ProBillActivity.class);
                break;
            case 9:
                intentToActivityWithoutParameter(this, CodeReplaceActivity.class);
                break;
            case 10:
                showMsg("当前版本:" + CheckVersion.getVersionName(this));
                break;
            case 11:
                chooseDialog.show();
                break;
            case 12:
                break;
            case 13:
                chooseDialog1.show();
                break;
            case 14:
                JDBeanNewOut.DataBean jdBeanNewOut = new JDBeanNewOut.DataBean();
                jdBeanNewOut.setJieDianName("溯源补码");
                jdBeanNewOut.setProcessID("14");
                jdBeanNewOut.setBillType("200");
                intentToActivityWithSParameter(MainActivity.this, BMBillActivity.class,PDApp.process,jdBeanNewOut);
                break;
            case 15:
                intentToActivityWithoutParameter(this, com.pda.yuanjing.pages.codehuan.CodeReplaceActivity.class);
                break;
            case 16:
                JDBeanNewOut.DataBean jdBeanNewOut1 = new JDBeanNewOut.DataBean();
                jdBeanNewOut1.setJieDianName("库存盘点");
                jdBeanNewOut1.setProcessID("16");
                jdBeanNewOut1.setBillType("300");
                intentToActivityWithSParameter(MainActivity.this, PDBillActivity.class,PDApp.process,jdBeanNewOut1);
                break;
            case 17:
                JDBeanNewOut.DataBean jdBeanNewOut3 = new JDBeanNewOut.DataBean();
                jdBeanNewOut3.setProcessID("17");
                jdBeanNewOut3.setBillType("400");
                intentToActivityWithSParameter(MainActivity.this, com.pda.yuanjing.pages.syyk.ScanfActivity.class,PDApp.process,jdBeanNewOut3);
                break;
            case 19:
                intentToActivityWithoutParameter(this, QueryActivity.class);
                break;
            case 20:
                JDBeanNewOut.DataBean jdBeanNewOut5 = new JDBeanNewOut.DataBean();
                jdBeanNewOut5.setProcessID("20");
                jdBeanNewOut5.setJieDianName("溯源统计");
                intentToActivityWithSParameter(MainActivity.this, TJActivity.class,PDApp.process,jdBeanNewOut5);
                break;
            case 21:
                JDBeanNewOut.DataBean jdBeanNewOut2 = new JDBeanNewOut.DataBean();
                jdBeanNewOut2.setJieDianName("销售出库");
                jdBeanNewOut2.setProcessID("21");
                jdBeanNewOut2.setBillType("800");
                intentToActivityWithSParameter(MainActivity.this, XSCKBillActivity.class,PDApp.process,jdBeanNewOut2);
                break;
            case 22:
                intentToActivityWithoutParameter(this, ModfiyPassActivity.class);
                break;
            case 23:
                intentToActivityWithoutParameter(this, SYKCActivity.class);
                break;
            case 24:
                JDBeanNewOut.DataBean jdBeanNewOut6 = new JDBeanNewOut.DataBean();
                jdBeanNewOut6.setJieDianName("节点盘点");
                jdBeanNewOut6.setProcessID("24");
                jdBeanNewOut6.setBillType("900");
                intentToActivityWithSParameter(MainActivity.this, JDBillActivity.class,PDApp.process,jdBeanNewOut6);
                break;
            case 25:
                JDBeanNewOut.DataBean jdBeanNewOut7 = new JDBeanNewOut.DataBean();
                jdBeanNewOut7.setJieDianName("托盘组装");
                jdBeanNewOut7.setProcessID("25");
                intentToActivityWithSParameter(MainActivity.this, TpzzActivity.class,PDApp.process,jdBeanNewOut7);
                break;
            case 26:
                JDBeanNewOut.DataBean jdBeanNewOut8 = new JDBeanNewOut.DataBean();
                jdBeanNewOut8.setJieDianName("数码清除");
                jdBeanNewOut8.setProcessID("26");
                intentToActivityWithSParameter(MainActivity.this, CodeClearActivity.class,PDApp.process,jdBeanNewOut8);
                break;
            case 27:
                JDBeanNewOut.DataBean jdBeanNewOut9 = new JDBeanNewOut.DataBean();
                jdBeanNewOut9.setJieDianName("溯源副码");
                jdBeanNewOut9.setProcessID("27");
                intentToActivityWithSParameter(MainActivity.this, FuCodeActivity.class,PDApp.process,jdBeanNewOut9);
                break;
            case 28:
                JDBeanNewOut.DataBean jdBeanNewOut10 = new JDBeanNewOut.DataBean();
                jdBeanNewOut10.setJieDianName("型号变更");
                jdBeanNewOut10.setProcessID("28");
                intentToActivityWithSParameter(MainActivity.this, BGActivity.class,PDApp.process,jdBeanNewOut10);
                break;
            case 29:
                JDBeanNewOut.DataBean jdBeanNewOut11 = new JDBeanNewOut.DataBean();
                jdBeanNewOut11.setJieDianName("溯源bom");
                jdBeanNewOut11.setProcessID("29");
                intentToActivityWithSParameter(MainActivity.this, bomQueryActivity.class,PDApp.process,jdBeanNewOut11);
                break;
            case 30:
                JDBeanNewOut.DataBean jdBeanNewOut12 = new JDBeanNewOut.DataBean();
                jdBeanNewOut12.setJieDianName("实验指示");
                jdBeanNewOut12.setProcessID("30");
                intentToActivityWithSParameter(MainActivity.this, SYZSActivity.class,PDApp.process,jdBeanNewOut12);
                break;
            case 31:
                JDBeanNewOut.DataBean jdBeanNewOut13 = new JDBeanNewOut.DataBean();
                jdBeanNewOut13.setJieDianName("溯源备注");
                jdBeanNewOut13.setProcessID("31");
                intentToActivityWithSParameter(MainActivity.this, BZActivity.class,PDApp.process,jdBeanNewOut13);
                break;
            default:
                if (messageWarp.getCode() > 100) {
                    showProgress();
                    getJDPage(messageWarp.getBillType(), messageWarp.getText());
                    hideProgress();
                }
                break;
        }
    }
}
